package com.gang.ssm.bos.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gang.ssm.bos.common.Page;
import com.gang.ssm.bos.system.bean.Role;
import com.gang.ssm.bos.system.mapper.RoleMapper;
import com.gang.ssm.bos.system.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private IdentityService identityService;
	
	@Override
	public List<Role> findAll() {
		return roleMapper.selectByExample(null);
	}

	@Override
	public void saveOrUpdate(Role role, String menuIds) {
		
		if(role.getId() != null) {
			roleMapper.updateByPrimaryKeySelective(role);
			
			roleMapper.deleteRoleMenuByRoleId(role.getId());
		} else {
			roleMapper.insertSelective(role);
		}
		
		Group group = new GroupEntity(role.getName());
		identityService.saveGroup(group);
		
		List<Integer> idList = new ArrayList<Integer>();
		for(String functionId : menuIds.split(",")) {
			idList.add(Integer.valueOf(functionId));
		}
		roleMapper.insertRoleAndMenu(role.getId(),idList);
	}

	@Override
	public List<Integer> findIdListByUserId(Integer id) {
		return roleMapper.findIdListByUserId(id);
	}

	@Override
	public void pageQuery(Page<Role> page) {
		
		page.setTotalCount((int)roleMapper.countByExample(null));
		List<Role> roleList = roleMapper.findByLimit((page.getPageNo() - 1)*page.getPageSize(),
						page.getPageSize());
		page.setResult(roleList);
	}

	@Override
	public Role findById(Integer id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public void deleteById(Integer id) {
		
		roleMapper.deleteRoleMenuByRoleId(id);
		roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public String findRoleCodeByRoleId(Integer roleId) {
		
		return roleMapper.findRoleCodeByRoleId(roleId);
	}

	@Override
	public List<String> findNameByUserId(Integer userId) {
		
		return roleMapper.findNameByUserId(userId);
	}

}
